<?php
namespace App\Http\Controllers\Api\Buz;

use App\Http\Controllers\Controller;
use App\Lib\BCMathLib;
use App\Lib\Code;
use App\Lib\SystemNumber;
use App\Models\RemitOrder;
use App\Repositories\Criteria\AuthUserCriteria;
use App\Repositories\Criteria\RemitSettingCriteria;
use App\Repositories\Criteria\TimeFilterCriteria;
use App\Repositories\Eloquent\AssetCountEloquent;
use App\Repositories\Eloquent\PlatSettingRepository;
use App\Repositories\Eloquent\WithdrawOrderRepository;
use App\Services\ApiResponseService;
use App\Services\RemitOrderService;
use App\Validators\Buz\WithdrawValidator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class WithdrawController extends Controller
{
    protected $orderRepository;

    public function __construct(WithdrawOrderRepository $withdrawOrderRepository)
    {
        $this->orderRepository = $withdrawOrderRepository;
        $this->orderRepository->pushCriteria(AuthUserCriteria::class);
    }

    public function index(Request $request)
    {
        $this->orderRepository->pushCriteria(new TimeFilterCriteria($request, 'created_at', false));
        $lists = $this->orderRepository
            ->orderBy('created_at', 'desc')
            ->paginate(15, [
                'plat_no', 'money', 'fee', 'ac_money',
                'status', 'disposal', 'bk_username', 'bk_category',
                'bk_account', 'bk_prov', 'bk_city', 'bk_branch',
                'bk_number', 'remark', 'ad_remark', 'created_at', 'updated_at'
                ]);
        return ApiResponseService::returnData($lists);
    }

    public function store(Request $request,
                          WithdrawValidator $validator,
                          RemitOrderService $remitOrderService,
                          PlatSettingRepository $platSettingRepository,
                          AssetCountEloquent $assetCountEloquent)
    {
        $data = $request->all(array_keys($validator->getRules('create')));
        $validator->with($data)->passesOrFail('create');

        $money = $data['money'];
        $user = Auth::user();

        $asset = $user->assets;
        //植入出款设置 条件
        $platSettingRepository->pushCriteria(RemitSettingCriteria::class);
        $setting = $platSettingRepository->first();
        $setting = $setting->value;

        //判断是否金额是否达到条件
        $code = $remitOrderService->isPassable($money, $setting);
        if ($code !== true) {
            return ApiResponseService::showError($code);
        }
        $fee = $remitOrderService->remitFee($money, $setting);
        $ac_money = bcadd($money, $fee, 2);
        if (bccomp($asset->available, $ac_money, 2) == -1) {
            return ApiResponseService::showError(Code::BALANCE_INSUFFICIENT);
        }
        $remit = new RemitOrder();
        $bank = $user->bank()->default()->first();
        DB::beginTransaction();
        try {
            $provCity = $bank->city;
            $remit->plat_no = SystemNumber::getWithdrawOrderNumber();
            $remit->batch_no = SystemNumber::getBatchNoNumber();
            $remit->uid = $user->id;
            $remit->classify = 0;
            $remit->status = 1;
            $remit->bk_username = $bank->username;
            $remit->bk_category = $bank->category;
            $remit->bk_account = $bank->account;
            $remit->bk_prov = $provCity->province;
            $remit->bk_city = $provCity->city;
            $remit->bk_branch = $bank->branch;
            $remit->bk_number = $bank->number;
            $remit->req_ip = $request->getClientIp();
            $remit->money = $money;
            $remit->fee = $fee;
            $remit->ac_money = $ac_money;
            $remit->save();
            $assetCountEloquent->operateAsset($user->id, 'withdrawFrozen', $ac_money);
            DB::commit();
            // todo: 此处若有结算接口 加入队列处理


        } catch (\Exception $exception) {
            DB::rollback();
            return ApiResponseService::showError(Code::FATAL_ERROR, $exception->getMessage());
        }
        return ApiResponseService::success(Code::SUCCESS);
    }
}
